package com.ywy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywy.common.rest.Result;
import com.ywy.search.service.ESService;
import com.ywy.service.PostService;
import com.ywy.vo.PostVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 管理员操作的Controller
 *
 * @author ywy
 * @date 2021/12/30 14:19
 */
@Controller
@RequestMapping("admin")
public class AdminController extends BaseController {
    @Autowired
    private PostService postService;
    @Autowired
    private ESService esService;

    /**
     * 初始化ES数据
     *
     * @return
     */
    @ResponseBody
    @PostMapping("initEsData")
    public Result initEsData() {
        int total = 0;
        int size = 10000;

        Page page = new Page<>();
        page.setSize(size);

        // 分页初始化ES数据
        for (int i = 1; i < 1000; i++) {
            page.setCurrent(i);
            IPage<PostVo> paging = postService.listByPage(page, null, null, null, null, null);
            int num = esService.initEsIndex(paging.getRecords());
            total += num;

            // 当一页查不出10000条的时候，说明是最后一页了
            if (paging.getRecords().size() < size) {
                break;
            }
        }
        return Result.success("ES索引初始化成功，共 " + total + " 条记录！", null);
    }
}
